// 页面加载时初始化数据
document.addEventListener("DOMContentLoaded", function () {
    loadCommunityPosts(); // 加载编程社区动态
    populateTags();       // 填充编程相关标签
    populateCategories(); // 填充编程相关分类
});

// 动态填充分类数据
const categories = ["学习心得", "问题求助", "开源项目", "算法探讨", "代码分享"];
function populateCategories() {
    const categorySelect = document.getElementById("post-category");
    categorySelect.innerHTML = ""; // 清空旧选项
    categories.forEach(category => {
        const option = document.createElement("option");
        option.value = category;
        option.textContent = category;
        categorySelect.appendChild(option);
    });
}

// 动态填充标签数据
const tags = ["算法", "前端", "后端", "数据库", "人工智能", "开源项目", "代码优化", "框架"];
function populateTags() {
    const tagsDiv = document.getElementById("post-tags");
    tagsDiv.innerHTML = ""; // 清空旧内容
    tags.forEach(tag => {
        const label = document.createElement("label");
        const checkbox = document.createElement("input");
        checkbox.type = "checkbox";
        checkbox.name = "tags";
        checkbox.value = tag;

        label.appendChild(checkbox);
        label.appendChild(document.createTextNode(tag));
        tagsDiv.appendChild(label);
    });
}

// 加载社区动态
function loadCommunityPosts() {
    fetch('/api/get-posts')
        .then(response => response.json())
        .then(data => {
            const postsSection = document.getElementById("community-posts");
            postsSection.innerHTML = ""; // 清空旧内容

            if (data.success) {
                data.posts.forEach(post => {
                    const postElement = document.createElement("div");
                    postElement.classList.add("post");

                    // 用户信息部分
                    const userInfo = document.createElement("div");
                    userInfo.classList.add("user-info");

                    const avatarImg = document.createElement("img");
                    avatarImg.classList.add("avatar");
                    // avatarImg.src = post.avatar || "../images/default-avatar.png";
                    avatarImg.src = post.avatar;
                    avatarImg.alt = `${post.username} 的头像`;

                    const username = document.createElement("span");
                    username.classList.add("username");
                    username.textContent = post.username;

                    userInfo.appendChild(avatarImg);
                    userInfo.appendChild(username);

                    // 内容部分
                    const content = document.createElement("p");
                    content.classList.add("content");
                    content.textContent = post.content;

                    // 代码片段部分
                    if (post.codeSnippet) {
                        const codeBlock = document.createElement("pre");
                        const code = document.createElement("code");
                        code.textContent = post.codeSnippet;
                        codeBlock.appendChild(code);
                        postElement.appendChild(codeBlock);
                    }

                    // 图片部分
                    if (post.image_url) {
                        const postImage = document.createElement("img");
                        postImage.classList.add("post-image");
                        postImage.src = new URL(post.image_url, window.location.origin).href;
                        postImage.alt = "文章图片";
                        postImage.onerror = () => {
                            // postImage.src = "../images/default-image.png";
                        };
                        postElement.appendChild(postImage);
                    }

                    // 元信息部分
                    const metaInfo = document.createElement("div");
                    metaInfo.classList.add("meta-info");
                    metaInfo.innerHTML = `
                        <span>分类: ${post.category}</span> |
                        <span>日期: ${post.date}</span>
                    `;

                    // 组合动态内容
                    postElement.appendChild(userInfo);
                    postElement.appendChild(content);
                    postElement.appendChild(metaInfo);

                    // 插入到社区动态区域
                    postsSection.appendChild(postElement);
                });
            } else {
                const errorMessage = document.createElement("p");
                errorMessage.textContent = data.message || "加载帖子失败。";
                postsSection.appendChild(errorMessage);
            }
        })
        .catch(error => console.error("Error fetching posts:", error));
}

// 提交新内容
function submitPost() {
    const form = document.querySelector("form");
    const formData = new FormData(form);

    // 获取图片文件
    const imageInput = document.getElementById("post-image");
    if (imageInput.files.length > 0) {
        formData.append("image", imageInput.files[0]);
    }

    fetch('/api/add-post', {
        method: 'POST',
        body: formData,
    })
        .then(response => response.json())
        .then(data => {
            if (data.success) {
                alert("发布成功！");
                loadCommunityPosts(); // 刷新动态
            } else {
                alert("发布失败：" + data.message);
            }
        })
        .catch(error => console.error("Error submitting post:", error));

    return false; // 阻止表单默认提交行为
}

